package com.yuexun.dhdoctor.module.personalPlan.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.baselistener.OnDataBackListener;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.personalPlan.bean.LockTimeBean;
import com.yuexun.dhdoctor.module.personalPlan.bean.OtherPlanBean;
import com.yuexun.dhdoctor.module.personalPlan.bean.PlanBean;
import com.yuexun.dhdoctor.module.personalPlan.model.impl.PlanMainModel;
import com.yuexun.dhdoctor.module.personalPlan.presenter.impl.PlanMainPresenter;
import com.yuexun.dhdoctor.module.personalPlan.ui.Act_PlanEdt;
import com.yuexun.dhdoctor.module.personalPlan.ui.view.IPlanMainView;
import com.yuexun.dhdoctor.util.DateUtil;
import com.yuexun.dhdoctor.widget.ToastDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/4/20 0020.
 */

public class Frag_MyPlan extends KJFragment implements IPlanMainView, OnDataBackListener {
    PlanMainPresenter presenter;
    Calendar calendar = Calendar.getInstance();
    int week_count = 0;
    @Bind(R.id.tv_week_title)
    TextView tvWeekTitle;
    @Bind(R.id.tv_week_date)
    TextView tvWeekDate;
    @Bind(R.id.task_weektime_mon)
    TextView taskWeektimeMon;
    @Bind(R.id.task_weektime_mon_am)
    TextView taskWeektimeMonAm;
    @Bind(R.id.task_weektime_mon_pm)
    TextView taskWeektimeMonPm;
    @Bind(R.id.task_weektime_tue)
    TextView taskWeektimeTue;
    @Bind(R.id.task_weektime_tue_am)
    TextView taskWeektimeTueAm;
    @Bind(R.id.task_weektime_tue_pm)
    TextView taskWeektimeTuePm;
    @Bind(R.id.task_weektime_wed)
    TextView taskWeektimeWed;
    @Bind(R.id.task_weektime_wed_am)
    TextView taskWeektimeWedAm;
    @Bind(R.id.task_weektime_wed_pm)
    TextView taskWeektimeWedPm;
    @Bind(R.id.task_weektime_thu)
    TextView taskWeektimeThu;
    @Bind(R.id.task_weektime_thu_am)
    TextView taskWeektimeThuAm;
    @Bind(R.id.task_weektime_thu_pm)
    TextView taskWeektimeThuPm;
    @Bind(R.id.task_weektime_fri)
    TextView taskWeektimeFri;
    @Bind(R.id.task_weektime_fri_am)
    TextView taskWeektimeFriAm;
    @Bind(R.id.task_weektime_fri_pm)
    TextView taskWeektimeFriPm;
    @Bind(R.id.task_weektime_sat)
    TextView taskWeektimeSat;
    @Bind(R.id.task_weektime_sat_am)
    TextView taskWeektimeSatAm;
    @Bind(R.id.task_weektime_sat_pm)
    TextView taskWeektimeSatPm;
    @Bind(R.id.task_weektime_sun)
    TextView taskWeektimeSun;
    @Bind(R.id.task_weektime_sun_am)
    TextView taskWeektimeSunAm;
    @Bind(R.id.task_weektime_sun_pm)
    TextView taskWeektimeSunPm;

    String[] dates;
    TextView[] tv_date, tv_date_am, tv_date_pm;
    Boolean[] tv_date_am_tag, tv_date_pm_tag;
    Map<String, PlanBean> map_plan = new HashMap<String, PlanBean>();//创建一个Map来存放

    Boolean isLock = true;//是否锁定，默认锁定
    Act_PlanEdt act_planEdt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.frag_my_plan, null);
        ButterKnife.bind(this, view);
        tv_date = new TextView[]{taskWeektimeMon, taskWeektimeTue, taskWeektimeWed, taskWeektimeThu, taskWeektimeFri, taskWeektimeSat, taskWeektimeSun};
        tv_date_am = new TextView[]{taskWeektimeMonAm, taskWeektimeTueAm, taskWeektimeWedAm, taskWeektimeThuAm, taskWeektimeFriAm, taskWeektimeSatAm, taskWeektimeSunAm};
        tv_date_pm = new TextView[]{taskWeektimeMonPm, taskWeektimeTuePm, taskWeektimeWedPm, taskWeektimeThuPm, taskWeektimeFriPm, taskWeektimeSatPm, taskWeektimeSunPm};
        tv_date_am_tag = new Boolean[]{false, false, false, false, false, false, false};
        tv_date_pm_tag = new Boolean[]{false, false, false, false, false, false, false};
        dates = new String[7];

        init();
        return view;
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        return null;
    }

    private void init() {
        presenter = new PlanMainPresenter(new PlanMainModel(), this);

        calendar.setTime(new Date());
        clear_date();
        searchLockTime();
//        set();
    }

    @Override
    public void onResume() {
        super.onResume();
        set();
    }


    private void searchLockTime() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        presenter.lockTime(params);
    }

    //请求本周计划
    private void set() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("startDate", DateUtil.getMondayOfThisWeek(calendar));
        params.put("endDate", DateUtil.getSundayOfThisWeek(calendar));
        presenter.getMyTask(params);
        setDateTitle();
        setDate(calendar);
    }

    //设置标题 日期
    private void setDateTitle() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月", Locale.getDefault());
        int weekOfMonth = calendar.get(Calendar.WEEK_OF_MONTH);
        tvWeekTitle.setText(formatter.format(calendar.getTime()));
        tvWeekDate.setText("第" + weekOfMonth + "周(" +
                DateUtil.getMondayOfThisWeek_Title(calendar) + "-" + DateUtil.getSundayOfThisWeek_Title(calendar) + ")");
    }

    private void setDate(Calendar calendar) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(calendar.getTime());
        SimpleDateFormat formatter = new SimpleDateFormat("MM-dd", Locale.getDefault());
        calendar1 = DateUtil.getMondayOfThisWeek_Calendar(calendar1);
        for (int i = 0; i < 7; i++) {
            dates[i] = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(calendar1.getTime());
            tv_date[i].setText(formatter.format(calendar1.getTime()));
            calendar1.add(Calendar.DATE, 1);
        }
    }

    @Override
    public void showTask(String s) {
        map_plan.clear();
        try {
            JSONObject jsonObject_all = new JSONObject(s);
            JSONArray datas = jsonObject_all.getJSONArray("datas");
            JSONObject data = datas.getJSONObject(0);
            Iterator<?> iterator = data.keys();
            while (iterator.hasNext()) { // 遍历每个key
                String key = (String) iterator.next();

                //切记用optJSONObject();用getJSONObject()在为null的时候会报错哦！！！
                JSONArray ob_array = data.optJSONArray(key);
                JSONObject ob = ob_array.getJSONObject(0);
                PlanBean planBean = null;
                if (ob != null) {   //记得判断哦！！
                    planBean = new PlanBean();
                    planBean.setAmpm(ob.optString("ampm"));
                    planBean.setContent(ob.optString("content"));
                    planBean.setPersonalId(ob.optInt("personalId"));
                    planBean.setPersonalName(ob.optString("personalName"));
                    planBean.setStartDatetime(ob.optString("startDatetime"));
                    planBean.setStateDescrption(ob.optString("stateDescrption"));
                    planBean.setState(ob.optInt("state"));
                    planBean.setStartDate(ob.optString("startDate"));
                    planBean.setPersonalScheduleId(ob.optString("personalScheduleId"));
                    map_plan.put(key, planBean);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        setPlan(map_plan);
    }

    @Override
    public void showOtherTask(ArrayList<OtherPlanBean.DatasEntity> datasEntity) {

    }

    @Override
    public void PullDownRefreshState(int state) {

    }

    @Override
    public void lockTime(LockTimeBean lockTimeBean) {
        if (lockTimeBean.getStatus().equals("200")) {
            if (lockTimeBean.getDatas().get(0).getState().equals("1")) {
                String lockTime = lockTimeBean.getDatas().get(0).getDate();
                String[] lockday = lockTime.split(" ");

                String deadline = DateUtil.getDayOfThisWeek(calendar, Integer.valueOf(lockday[0]));
                deadline = deadline + " " + lockday[1];

                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
                int state = DateUtil.compare_date(formatter.format(new Date()), deadline);
//                int state = DateUtil.compare_date("2016-09-16 08:00","2016-09-16 07:00");
                isLock = state == 1;
            } else {
                isLock = false;
            }
        }
    }

    private void setPlan(Map<String, PlanBean> map) {
        if (map.size() > 0.) {
            for (String key : map.keySet()) {
                switch (key.substring(0, 1)) {
                    case "1":
                        switch (key.substring(1, 2)) {
                            case "1":
                                tv_date_am[0].setText(map.get(key).getContent());
                                tv_date_am_tag[0] = true;
                                break;
                            case "2":
                                tv_date_pm[0].setText(map.get(key).getContent());
                                tv_date_pm_tag[0] = true;
                                break;
                        }
                        break;
                    case "2":
                        switch (key.substring(1, 2)) {
                            case "1":
                                tv_date_am[1].setText(map.get(key).getContent());
                                tv_date_am_tag[1] = true;
                                break;
                            case "2":
                                tv_date_pm[1].setText(map.get(key).getContent());
                                tv_date_pm_tag[1] = true;
                                break;
                        }
                        break;
                    case "3":
                        switch (key.substring(1, 2)) {
                            case "1":
                                tv_date_am[2].setText(map.get(key).getContent());
                                tv_date_am_tag[2] = true;
                                break;
                            case "2":
                                tv_date_pm[2].setText(map.get(key).getContent());
                                tv_date_pm_tag[2] = true;
                                break;
                        }
                        break;
                    case "4":
                        switch (key.substring(1, 2)) {
                            case "1":
                                tv_date_am[3].setText(map.get(key).getContent());
                                tv_date_am_tag[3] = true;
                                break;
                            case "2":
                                tv_date_pm[3].setText(map.get(key).getContent());
                                tv_date_pm_tag[3] = true;
                                break;
                        }
                        break;
                    case "5":
                        switch (key.substring(1, 2)) {
                            case "1":
                                tv_date_am[4].setText(map.get(key).getContent());
                                tv_date_am_tag[4] = true;
                                break;
                            case "2":
                                tv_date_pm[4].setText(map.get(key).getContent());
                                tv_date_pm_tag[4] = true;
                                break;
                        }
                        break;
                    case "6":
                        switch (key.substring(1, 2)) {
                            case "1":
                                tv_date_am[5].setText(map.get(key).getContent());
                                tv_date_am_tag[5] = true;
                                break;
                            case "2":
                                tv_date_pm[5].setText(map.get(key).getContent());
                                tv_date_pm_tag[5] = true;
                                break;
                        }
                        break;
                    case "7":
                        switch (key.substring(1, 2)) {
                            case "1":
                                tv_date_am[6].setText(map.get(key).getContent());
                                tv_date_am_tag[6] = true;
                                break;
                            case "2":
                                tv_date_pm[6].setText(map.get(key).getContent());
                                tv_date_pm_tag[6] = true;
                                break;
                        }
                        break;
                }
            }
        }
    }

    private void clear_date() {
        for (int i = 0; i < 7; i++) {
            tv_date_am[i].setText("");
            tv_date_am_tag[i] = false;
            tv_date_pm[i].setText("");
            tv_date_pm_tag[i] = false;
        }
    }

    @OnClick({R.id.task_weektime_mon_am, R.id.task_weektime_mon_pm, R.id.task_weektime_tue_am, R.id.task_weektime_tue_pm,
            R.id.task_weektime_wed_am, R.id.task_weektime_wed_pm, R.id.task_weektime_thu_am, R.id.task_weektime_thu_pm,
            R.id.task_weektime_fri_am, R.id.task_weektime_fri_pm, R.id.task_weektime_sat_am, R.id.task_weektime_sat_pm,
            R.id.task_weektime_sun_am, R.id.task_weektime_sun_pm, R.id.task_back, R.id.task_now, R.id.task_next})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.task_weektime_mon_am:
                start_activity(dates[0] + " 周一", "上午", tv_date_am[0].getText().toString(), tv_date_am_tag[0], "11");
                break;
            case R.id.task_weektime_mon_pm:
                start_activity(dates[0] + " 周一", "下午", tv_date_pm[0].getText().toString(), tv_date_pm_tag[0], "12");
                break;
            case R.id.task_weektime_tue_am:
                start_activity(dates[1] + " 周二", "上午", tv_date_am[1].getText().toString(), tv_date_am_tag[1], "21");
                break;
            case R.id.task_weektime_tue_pm:
                start_activity(dates[1] + " 周二", "下午", tv_date_pm[1].getText().toString(), tv_date_pm_tag[1], "22");
                break;
            case R.id.task_weektime_wed_am:
                start_activity(dates[2] + " 周三", "上午", tv_date_am[2].getText().toString(), tv_date_am_tag[2], "31");
                break;
            case R.id.task_weektime_wed_pm:
                start_activity(dates[2] + " 周三", "下午", tv_date_pm[2].getText().toString(), tv_date_pm_tag[2], "32");
                break;
            case R.id.task_weektime_thu_am:
                start_activity(dates[3] + " 周四", "上午", tv_date_am[3].getText().toString(), tv_date_am_tag[3], "41");
                break;
            case R.id.task_weektime_thu_pm:
                start_activity(dates[3] + " 周四", "下午", tv_date_pm[3].getText().toString(), tv_date_pm_tag[3], "42");
                break;
            case R.id.task_weektime_fri_am:
                start_activity(dates[4] + " 周五", "上午", tv_date_am[4].getText().toString(), tv_date_am_tag[4], "51");
                break;
            case R.id.task_weektime_fri_pm:
                start_activity(dates[4] + " 周五", "下午", tv_date_pm[4].getText().toString(), tv_date_pm_tag[4], "52");
                break;
            case R.id.task_weektime_sat_am:
                start_activity(dates[5] + " 周六", "上午", tv_date_am[5].getText().toString(), tv_date_am_tag[5], "61");
                break;
            case R.id.task_weektime_sat_pm:
                start_activity(dates[5] + " 周六", "下午", tv_date_pm[5].getText().toString(), tv_date_pm_tag[5], "62");
                break;
            case R.id.task_weektime_sun_am:
                start_activity(dates[6] + " 周日", "上午", tv_date_am[6].getText().toString(), tv_date_am_tag[6], "71");
                break;
            case R.id.task_weektime_sun_pm:
                start_activity(dates[6] + " 周日", "下午", tv_date_pm[6].getText().toString(), tv_date_pm_tag[6], "72");
                break;
            case R.id.task_back:
                calendar.add(Calendar.DATE, -7);
                week_count--;
                clear_date();
                set();
                break;
            case R.id.task_now:
                calendar.setTime(new Date());
                week_count = 0;
                clear_date();
                set();
                break;
            case R.id.task_next:
                calendar.add(Calendar.DATE, 7);
                week_count++;
                clear_date();
                set();
                break;
        }
    }

    private void start_activity(String date, String time, String content, Boolean iscreate, String key) {
        if (week_count == 1) {
            if (isLock) {
                new ToastDialog(getActivity(), "计划已锁定，无法修改").show();
            } else {
                Bundle bundle = new Bundle();
                Intent intent = new Intent(getActivity(), Act_PlanEdt.class);
                bundle.putSerializable("date", date);
                bundle.putSerializable("time", time);
                bundle.putSerializable("content", content);
                bundle.putSerializable("iscreate", iscreate);
                bundle.putSerializable("key", key);
                if (iscreate)
                    bundle.putSerializable("personalScheduleId", map_plan.get(key).getPersonalScheduleId());
                intent.putExtras(bundle);
//                startActivityForResult(intent, 1);
                startActivity(intent);
            }
        } else if (week_count <= 0) {
            new ToastDialog(getActivity(), "历史记录不能编辑！").show();
        } else if (week_count > 1) {
            Bundle bundle = new Bundle();
            Intent intent = new Intent(getActivity(), Act_PlanEdt.class);
            bundle.putSerializable("date", date);
            bundle.putSerializable("time", time);
            bundle.putSerializable("content", content);
            bundle.putSerializable("iscreate", iscreate);
            bundle.putSerializable("key", key);
            if (iscreate)
                bundle.putSerializable("personalScheduleId", map_plan.get(key).getPersonalScheduleId());
            intent.putExtras(bundle);
            startActivity(intent);
//            startActivityForResult(intent, 1);
        }
    }

    @Override
    public void showData(Bundle bundle) {
        if (bundle != null) {
            if (bundle.getString("type").equals("200")) {
                PlanBean planBean = (PlanBean) bundle.getSerializable("planBean");
                map_plan.put(bundle.getString("key"), planBean);
                setPlan(map_plan);
            } else if (bundle.getString("type").equals("201")) {
                map_plan.get(bundle.getString("key")).setContent(bundle.getString("content"));
                setPlan(map_plan);
            }

        }
    }
}
